from models.order import Order
from models.product import Product
from strategies.discount_strategy import DiscountStrategy

class ShoppingCart:
    def __init__(self):
        self.items = {}
        self.discount_strategy = None

    # 购物车操作方法（同原始代码）
    def add_item(self, product, quantity):
        if product.stock < quantity:
            print(f"错误：{product.name} 库存不足，当前库存为 {product.stock}。")
            return
        self.items[product] = self.items.get(product, 0) + quantity
        print(f"已添加 {quantity} 个 {product.name} 到购物车。")

    def remove_item(self, product, quantity):
        if product not in self.items:
            print("错误：商品不在购物车中。")
            return
        if self.items[product] <= quantity:
            del self.items[product]
        else:
            self.items[product] -= quantity
        print(f"已从购物车移除 {quantity} 个 {product.name}。")

    def set_discount_strategy(self, strategy):
        self.discount_strategy = strategy

    def calculate_total(self):
        total = sum(p.price * q for p, q in self.items.items())
        return self.discount_strategy.apply_discount(total) if self.discount_strategy else total

    def checkout(self):
        if not self.items:
            print("购物车为空，无法结账。")
            return None
        total = self.calculate_total()
        order = Order(self.items.copy(), total)
        for product, quantity in self.items.items():
            product.stock -= quantity
        self.items.clear()
        print("结账成功，订单已生成。")
        return order